package com.kai.mqtt.auth.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.kai.mqtt.auth.entity.MqttAcl;
import com.kai.mqtt.auth.mapper.MqttAclMapper;
import com.kai.mqtt.auth.service.IMqttAclService;
import com.kai.mqtt.data.PageResult;
import com.kai.mqtt.data.request.MqttAclRequest;
import com.kai.mqtt.data.request.MqttAclUpdateRequest;
import com.kai.mqtt.data.request.PageMqttAclRequest;
import com.kai.mqtt.data.response.MqttAclResponse;
import com.kai.mqtt.enums.AclActionEnum;
import com.kai.mqtt.enums.AclPermissionEnum;
import com.kai.mqtt.exception.BusinessException;
import com.kai.mqtt.util.TopicUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author weijk
 * @since 2024/8/18
 */
@Service
public class MqttAclServiceImpl extends ServiceImpl<MqttAclMapper, MqttAcl> implements IMqttAclService {

    /**
     * 创建 acl
     *
     * @param request 参数
     * @return 结果
     */
    @Override
    public Boolean createAcl(MqttAclRequest request) {
        MqttAcl mqttAcl = new MqttAcl();
        BeanUtils.copyProperties(request, mqttAcl);
        mqttAcl.setCreateDatetime(LocalDateTime.now())
                .setUpdateDatetime(LocalDateTime.now());

        return this.save(mqttAcl);
    }

    /**
     * 更新 acl
     *
     * @param request 参数
     * @return 结果
     */
    @Override
    public Boolean updateAcl(MqttAclUpdateRequest request) {
        MqttAcl mqttAcl = this.getById(request.getId());
        if (Objects.isNull(mqttAcl)) {
            throw new BusinessException("授权不存在");
        }

        BeanUtils.copyProperties(request, mqttAcl);
        mqttAcl.setUpdateDatetime(LocalDateTime.now());

        return this.updateById(mqttAcl);
    }

    /**
     * 删除 acl
     *
     * @param id id
     * @return 结果
     */
    @Override
    public Boolean deleteAcl(Integer id) {
        return this.removeById(id);
    }

    /**
     * 分页查询 acl 列表
     *
     * @param request 参数
     * @return acl 列表
     */
    @Override
    public PageResult<MqttAclResponse> pageAcl(PageMqttAclRequest request) {
        IPage<MqttAcl> mqttAclIPage = this.lambdaQuery()
                .eq(Objects.nonNull(request.getPermission()), MqttAcl::getPermission, request.getPermission())
                .eq(StringUtils.hasText(request.getUsername()), MqttAcl::getUsername, request.getUsername())
                .eq(Objects.nonNull(request.getAction()), MqttAcl::getAction, request.getAction())
                .like(StringUtils.hasText(request.getTopic()), MqttAcl::getTopic, request.getTopic())
                .page(new Page<>(request.getPageIndex(), request.getPageSize()));

        List<MqttAcl> mqttAclList = mqttAclIPage.getRecords();
        if (CollectionUtils.isEmpty(mqttAclList)) {
            return PageResult.success(Lists.newArrayList(), mqttAclIPage.getCurrent(), mqttAclIPage.getSize(), mqttAclIPage.getTotal());
        }

        List<MqttAclResponse> responses = mqttAclList.stream()
                .map(mqttAcl -> {
                    MqttAclResponse response = new MqttAclResponse();
                    BeanUtils.copyProperties(mqttAcl, response);

                    return response;
                }).toList();

        return PageResult.success(responses, mqttAclIPage.getCurrent(), mqttAclIPage.getSize(), mqttAclIPage.getTotal());
    }

    /**
     * 校验 topic
     *
     * @param username   用户名
     * @param clientId   客户端 id
     * @param actionEnum 订阅或发布
     * @param topic      主题
     * @return true-成功，false-失败
     */
    @Override
    public Boolean checkValid(String username, String clientId, AclActionEnum actionEnum, String topic) {
        List<MqttAcl> mqttAclList = this.lambdaQuery()
                .eq(MqttAcl::getUsername, username)
                .in(MqttAcl::getAction, AclActionEnum.SUB_AND_PUB.getCode(), actionEnum.getCode())
                .list();

        boolean flag = true;
        for (MqttAcl mqttAcl : mqttAclList) {
            if (Objects.equals(mqttAcl.getPermission(), AclPermissionEnum.ALLOW.getCode())) {
                if (TopicUtil.match(mqttAcl.getTopic(), topic)) {
                    return true;
                } else {
                    flag = false;
                }
            } else {
                if (TopicUtil.match(mqttAcl.getTopic(), topic)) {
                    return false;
                }
            }
        }

        return flag;
    }
}
